<?php

namespace App\Http\Controllers\Api\v1;

use App\Http\Controllers\Controller;
use App\Http\Request\Api\v1\User\InfoUpdateRequest;
use App\Http\Request\Api\v1\User\PasswordRetrieveRequest;
use App\Http\Request\Api\v1\User\PasswordUpdateRequest;
use App\Models\Arts\SmsCodeModel;
use App\Models\Arts\UserModel;
use App\Utils\AppResult;
use App\Utils\Common;
use App\Utils\Control\AuthUser;
use App\Utils\LogUtil;
use Illuminate\Support\Facades\DB;

/**
 * 通行证
 * PassportController
 * Class WxController
 * @package App\Http\Controllers\Api\v1
 */
class UserController extends Controller
{
    // 日志模块名称
    const LOG_MODULE = 'v1/UserController';

    /**
     * 用户基本信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function info()
    {
        // 用户登录信息
        $user = AuthUser::getInstance()->get();

        $userInfo = UserModel::getUserInfoByUserId($user['id']);
        return AppResult::response200('success', [
            'user_id'    => $userInfo['id'],
            'nickname'   => $userInfo['nickname'],
            'head_img'   => str_contains($userInfo['head_img'], 'http') ? $userInfo['head_img'] : Common::getHttp($userInfo['head_img']),
            'sex'        => $userInfo['sex'],
            'phone'      => Common::replaceSensitiveStr((string)$userInfo['phone'], 3, 4),
            'full_phone' => $userInfo['phone'],
        ]);
    }

    /**
     * 更新用户头像和昵称
     *
     * @param InfoUpdateRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function infoUpdate(InfoUpdateRequest $request)
    {
        // 参数接管
        $params = $request->all();

        // 用户登录信息
        $user = AuthUser::getInstance()->get();

        $data = [
            'nickname' => $params['nickname'],
            'head_img' => $params['head_img']
        ];

        if (!UserModel::edit($user['id'], $data)) {
            return AppResult::response201('操作失败，请重试！');
        }

        return AppResult::response200('操作成功！');
    }

    /**
     * 密码修改
     * @param PasswordUpdateRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function passwordUpdate(PasswordUpdateRequest $request)
    {
        // 参数接管
        $params = $request->all();

        // 用户登录信息
        $user = AuthUser::getInstance()->get();

        DB::beginTransaction();
        try {
            // 验证码校验
            $code = SmsCodeModel::AuthCode($user['phone'], $params['code']);
            LogUtil::warning('校验验证码结果', self::LOG_MODULE, __FUNCTION__, $code);
            if ($code['code'] != 200) {
                DB::rollBack();
                return AppResult::response201($code['msg'] ?? '验证码错误，或已过期！');
            }

            if (!UserModel::edit($user['id'], ['password' => $params['password']])) {
                DB::rollBack();
                return AppResult::response201('操作失败，请重试！');
            }

            DB::commit();
            return AppResult::response200('操作成功！');
        } catch (\Exception $e) {
            DB::rollBack();
            LogUtil::warning('系统错误', self::LOG_MODULE, __FUNCTION__, $e);
            return AppResult::response500('系统请求超时.');
        }
    }

    /**
     * 手机号验证码 重置密码
     *
     * @param PasswordRetrieveRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function passwordRetrieve(PasswordRetrieveRequest $request)
    {
        // 参数接管
        $params = $request->all();

        // 查询用户信息
        list($exists, $user_id) = UserModel::checkExists(phone: $params['phone']);
        if (!$exists) {
            return AppResult::response201('当前手机号不存在！');
        }

        DB::beginTransaction();
        try {
            // 验证码校验
            $code = SmsCodeModel::AuthCode($params['phone'], $params['code']);
            LogUtil::warning('校验验证码结果', self::LOG_MODULE, __FUNCTION__, $code);
            if ($code['code'] != 200) {
                DB::rollBack();
                return AppResult::response201($code['msg'] ?? '验证码错误，或已过期！');
            }

            if (!UserModel::edit($user_id, ['password' => $params['password']])) {
                DB::rollBack();
                return AppResult::response201('操作失败，请重试！');
            }

            DB::commit();
            return AppResult::response200('操作成功！');
        } catch (\Exception $e) {
            DB::rollBack();
            LogUtil::warning('系统错误', self::LOG_MODULE, __FUNCTION__, $e);
            return AppResult::response500('系统请求超时.');
        }
    }
}
